package com.xingongchang.baolebei.activity;


import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.baolelei.Threelogin.AccessTokenKeeper;
import com.baolelei.Threelogin.Constants;
import com.external.androidquery.callback.AjaxStatus;
import com.insthub.BeeFramework.activity.BaseActivity;
import com.insthub.BeeFramework.model.BusinessResponse;
import com.insthub.BeeFramework.view.ToastView;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.User;
import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xingongchang.baolebei.R;
import com.xingongchang.baolebei.model.LoginModel;
import com.xingongchang.baolebei.model.ProtocolConst;

public class SigninActivity extends BaseActivity implements OnClickListener,
		BusinessResponse {

	private ImageView back;
	private ImageView login;

	private EditText userName;
	private EditText password;
	private TextView register;

	private String name;
	private String psd;
	private LoginModel loginModel;
	private ProgressDialog pd = null;
	// 第三方登陆button2
	Button button, button2;
	private UserInfo mInfo;
	private Tencent mTencent;
	public static QQAuth mQQAuth;
	/** 注意：SsoHandler 仅当 SDK 支持 SSO 时有效 */
	private SsoHandler mSsoHandler;
	/** 微博 Web 授权类，提供登陆等功能 */
	private WeiboAuth mWeiboAuth;
	/** 封装了 "access_token"，"expires_in"，"refresh_token"，并提供了他们的管理功能 */
	private Oauth2AccessToken mAccessToken;
	 UsersAPI  mUsersAPI;
	private SharedPreferences share;
	private SharedPreferences.Editor editor;
	String openid;

	String uid;
	String nickname = "";
	String imgurl = "";
	ProgressDialog progressDialog;
	int type;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.signin);
		// 创建微博实例
		share = getSharedPreferences("sns", Context.MODE_PRIVATE);
		editor = share.edit();
		mWeiboAuth = new WeiboAuth(this, Constants.APP_KEY,
				Constants.REDIRECT_URL, Constants.SCOPE);
		mQQAuth = QQAuth.createInstance(Constants.QQAPP_ID,
				this.getApplicationContext());
		mTencent = Tencent.createInstance(Constants.QQAPP_ID,
				this.getApplicationContext());
		// SSO授权免登录
		// 从 SharedPreferences 中读取上次已保存好 AccessToken 等信息，
		// 第一次启动本应用，AccessToken 不可用
		mAccessToken = AccessTokenKeeper.readAccessToken(this);
		back = (ImageView) findViewById(R.id.login_back);
		login = (ImageView) findViewById(R.id.login_login);
		userName = (EditText) findViewById(R.id.login_name);
		password = (EditText) findViewById(R.id.login_password);
		register = (TextView) findViewById(R.id.login_register);
		register.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
		button = (Button) findViewById(R.id.xinlang);
		button2 = (Button) findViewById(R.id.dexun);
		back.setOnClickListener(this);
		login.setOnClickListener(this);
		register.setOnClickListener(this);
		button.setOnClickListener(this);
		button2.setOnClickListener(this);
		loginModel = new LoginModel(SigninActivity.this);
		loginModel.addResponseListener(this);
	}

	@Override
	public void onClick(View v) {
		Resources resource = (Resources) getBaseContext().getResources();
		String usern = resource.getString(R.string.user_name_cannot_be_empty);
		String pass = resource.getString(R.string.password_cannot_be_empty);
		String hold = resource.getString(R.string.hold_on);
		Intent intent;
		switch (v.getId()) {
		case R.id.login_back:
			finish();
			CloseKeyBoard();
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			break;
		case R.id.login_login:
			name = userName.getText().toString();
			psd = password.getText().toString();
			if ("".equals(name)) {
				ToastView toast = new ToastView(this, usern);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else if ("".equals(psd)) {
				ToastView toast = new ToastView(this, pass);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			} else {
				loginModel.login(name, psd);
				CloseKeyBoard();
				pd = new ProgressDialog(SigninActivity.this);
				pd.setMessage(hold);
				pd.show();
			}
			break;
		case R.id.login_register:
			intent = new Intent(this, SignupActivity.class);
			startActivityForResult(intent, 1);
			break;
		case R.id.xinlang:
			if (mAccessToken.isSessionValid() && mAccessToken != null) {
//				String uid = share.getString("uid", "");
//				type=2;
//				loginModel.snsLogin(uid, "login",type);
				mSsoHandler = new SsoHandler(this, mWeiboAuth);
				mSsoHandler.authorize(new AuthListener());
			} else {
				mSsoHandler = new SsoHandler(this, mWeiboAuth);
				mSsoHandler.authorize(new AuthListener());
			}
			break;
		case R.id.dexun:
			    onClickLogin();
			break;
		}

	}


	private void onClickLogin() {
		if (!mQQAuth.isSessionValid())
		{
			IUiListener listener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					progressDialog = new ProgressDialog(SigninActivity.this);
					progressDialog.setMessage("获取数据中,请稍后...");
					progressDialog.show();
					updateUserInfo();
				}
			};
			mTencent.login(this, "get_simple_userinfo", listener);
	 }else{
		 mTencent.logout(getApplicationContext());
		 IUiListener listener = new BaseUiListener() {
				@Override
				protected void doComplete(JSONObject values) {
					progressDialog = new ProgressDialog(SigninActivity.this);
					progressDialog.setMessage("获取数据中,请稍后...");
					progressDialog.show();
					updateUserInfo();
				}
			};
		 mTencent.login(this, "get_simple_userinfo", listener);
	   }
	}

	private class BaseUiListener implements IUiListener {
		@Override
		public void onComplete(Object response) {
			openid = ((JSONObject) response).optString("openid");
			editor.putString("openid", openid);
			editor.commit();
			doComplete((JSONObject) response);
		}

		protected void doComplete(JSONObject values) {
		}

		@Override
		public void onError(UiError e) { 
		}

		@Override
		public void onCancel() {
			
		}
	}

	Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 0) {
				JSONObject response = (JSONObject) msg.obj;
				if (response.has("nickname")) {
					try {
						imgurl = response.getString("figureurl_qq_2");
						nickname = response.getString("nickname");
						progressDialog.dismiss();
						type=1;
						loginModel.snsLogin(openid, "login", type);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

	};

	private void updateUserInfo() {

		if (mQQAuth != null && mQQAuth.isSessionValid()) {
			IUiListener listener = new IUiListener() {
				@Override
				public void onError(UiError e) {
					// TODO Auto-generated method stub
					Toast.makeText(SigninActivity.this, "失败", Toast.LENGTH_SHORT);
				}
				@Override
				public void onComplete(final Object response) {
					Message msg = new Message();
					msg.obj = response;
					msg.what = 0;
					mHandler.sendMessage(msg);
				}
				@Override
				public void onCancel() {
				}
			};

			mInfo = new UserInfo(this, mQQAuth.getQQToken());
			mInfo.getUserInfo(listener);

		} else {
			Toast.makeText(SigninActivity.this, "QQ登录授权失败", Toast.LENGTH_SHORT);
		}
	}

	/**
	 * 微博认证授权回调类。 1. SSO 授权时，需要在 {@link #onActivityResult} 中调用
	 * {@link SsoHandler#authorizeCallBack} 后， 该回调才会被执行。 2. 非 SSO
	 * 授权时，当授权结束后，该回调就会被执行。 当授权成功后，请保存该 access_token、expires_in、uid 等信息到
	 * SharedPreferences 中。
	 */
	class AuthListener implements WeiboAuthListener {

		@Override
		public void onComplete(Bundle values) {
			progressDialog = new ProgressDialog(SigninActivity.this);
			progressDialog.setMessage("获取数据中,请稍后...");
			progressDialog.show();
			// 从 Bundle 中解析 Token
			mAccessToken = Oauth2AccessToken.parseAccessToken(values);
			if (mAccessToken.isSessionValid() && mAccessToken != null) {
				// 保存 Token 到 SharedPreferences
				AccessTokenKeeper.writeAccessToken(SigninActivity.this,
						mAccessToken);
				   // 获取当前已保存过的 Token
		        mAccessToken = AccessTokenKeeper.readAccessToken(SigninActivity.this);
		        // 获取用户信息接口
		        mUsersAPI = new UsersAPI(mAccessToken);
		        long uid = Long.parseLong(mAccessToken.getUid());
                mUsersAPI.show(uid, mListener);
			} else {
			}
		}

		@Override
		public void onCancel() {
		}

		@Override
		public void onWeiboException(WeiboException e) {
		}
	}
	
	
	RequestListener mListener = new RequestListener() {
		@Override
		public void onComplete(String response) {
			if (!TextUtils.isEmpty(response)) {
				// 调用 User#parse 将JSON串解析成User对象
				User user = User.parse(response);
				if(user != null){
					openid = user.idstr;
					nickname = user.screen_name;
					imgurl = user.avatar_large;
					editor.putString("uid", openid);
					editor.commit();
					progressDialog.dismiss();
					type=2;
					loginModel.snsLogin(openid, "login",type);
				} else {
                    Toast.makeText(SigninActivity.this, response, Toast.LENGTH_LONG).show();
                }
			}
		}

		@Override
		public void onWeiboException(WeiboException arg0) {
			
		}
		
	};


	@Override
	public void OnMessageResponse(String url, JSONObject jo, AjaxStatus status)
			throws JSONException {
		if (url.endsWith(ProtocolConst.SIGNIN)) {
			if (loginModel.responseStatus.succeed == 1) {
				pd.dismiss();
				Intent intent = new Intent();
				intent.putExtra("login", true);
				setResult(Activity.RESULT_OK, intent);
				editor.putInt("jueding",1).commit();
				finish();
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}else if(loginModel.responseStatus.succeed == 0){
				pd.dismiss();	
			}

		} else if (url.endsWith(ProtocolConst.DISANFANG)) {
			if(loginModel.succeed==1){
				Intent intent=new Intent(SigninActivity.this,BaolebeiActivity.class);
				startActivity(intent);
				finish();
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}else if(loginModel.succeed==2){
				Intent intent=new Intent(SigninActivity.this,CompileActivity.class);
				intent.putExtra("open_Id", openid);
				intent.putExtra("user_type", type);
				startActivity(intent);
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}
			Toast.makeText(SigninActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == 1) {
			if (data != null) {
				Intent intent = new Intent();
				intent.putExtra("login", true);
				setResult(Activity.RESULT_OK, intent);
				finish();
				overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}
		}
		/**
		 * 当 SSO 授权 Activity 退出时，该函数被调用。
		 * 
		 * @see {@link Activity#onActivityResult}
		 */
		// SSO 授权回调
		// 重要：发起 SSO 登陆的 Activity 必须重写 onActivityResult
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
			progressDialog.show();
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			finish();
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
		}
		return true;
	}

	// 关闭键盘
	public void CloseKeyBoard() {
		userName.clearFocus();
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(userName.getWindowToken(), 0);
	}
}
